// index.js
import { apiClient, apiRoutes } from "../../utils/api";
const app = getApp();
import * as echarts from '../../ec-canvas/echarts';

function initChart(canvas, width, height, dpr) {
  const chart = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr
  });
  canvas.setChart(chart);
  return chart;
}

Page({
  data: {
    date: "",
    today: "",
    devices: [],
    device_picker_index: 0,
    chartOption: {}, //初始为空，组件chart不setOption
    isLoading: false,
    ec: {
      onInit: initChart
    },
    //下面数据仅用于调试
    example_option: {
      title: {
        text: '测试下面legend的红色区域不应被裁剪',
        left: 'center'
      },
      legend: {
        data: ['A', 'B', 'C'],
        top: 50,
        left: 'center',
        backgroundColor: 'red',
        z: 100
      },
      grid: {
        containLabel: true
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
        // show: false
      },
      yAxis: {
        x: 'center',
        type: 'value',
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
        // show: false
      },
      series: [{
        name: 'A',
        type: 'line',
        smooth: true,
        data: [18, 36, 65, 30, 78, 40, 33]
      }, {
        name: 'B',
        type: 'line',
        smooth: true,
        data: [12, 50, 51, 35, 70, 30, 20]
      }, {
        name: 'C',
        type: 'line',
        smooth: true,
        data: [10, 30, 31, 50, 40, 20, 10]
      }]
    }
  },
  // 初始化日期
  init_date() {
    let now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    let day = now.getDate();

    month = month < 10 ? '0' + month : month;
    day = day < 10 ? '0' + day : day;
    const today = `${year}-${month}-${day}`;

    this.setData({
      date: today,
      today: today
    });
  },

  // 获取设备列表
  fetchDevices() {
    apiClient.get(apiRoutes.devices).then(res => {
      console.log(res.data)
      if (res.data) {
        // 预处理数据，合并多个属性
        let devices = []
        const userrole = wx.getStorageSync('role')
        // console.log(userrole)
        if (userrole == "超级管理员"){
          devices = res.data.map(item => ({
            ...item,
            displayName: `${item.name} (组织id:${item.organization})`
          }));
        } else {
          devices = res.data.map(item => ({
            ...item,
            displayName: item.name
          }));
        }
        this.setData({
          devices,
          device_picker_index: 0
        });
      } else {
        wx.showToast({
          title: '数据获取失败',
          icon: 'none'
        });
      }
    }).catch(err => {
      console.error("获取设备列表失败", err);
      wx.showToast({
        title: '获取设备列表失败',
        icon: 'none'
      });
    });
  },

  // 获取图表数据
  fetchChartData() {
    if (!this.data.date || this.data.devices.length === 0) return;

    this.setData({ isLoading: true });

    const device = this.data.devices[this.data.device_picker_index];
    const date = this.data.date;

    apiClient.get(`${apiRoutes.device_data}${device.id}/${date}/`)
      .then(res => {
        if (res.data) {
          const option = this.formatOption(res.data);
          this.setData({ chartOption: option });
        } else {
          wx.showToast({
            title: '暂无数据',
            icon: 'none'
          });
        }
      })
      .catch(err => {
        console.error("获取图表数据失败", err);
        wx.showToast({
          title: '获取数据失败',
          icon: 'none'
        });
      })
      .finally(() => {
        this.setData({ isLoading: false });
      });
  },

  // 格式化图表配置
  formatOption(data) {
    let min = null, max = null;

    // 计算最小最大值
    data.series.forEach(element => {
      element.data.forEach(value => {
        if (min === null || value < min) min = value;
        if (max === null || value > max) max = value;
      });
    });

    // 添加一些边距
    const range = max - min;
    min -= range * 0.1;
    max += range * 0.1;

    return {
      title: {
        text: data.title_text,
        left: 'center'
      },
      legend: {
        data: data.legend_data,
        top: 20,
        left: 'center'
      },
      grid: {
        containLabel: true,
        left: '2%',
        right: '5%',
        top: '20%',
        bottom: '10%'
      },
      tooltip: {
        show: true,
        trigger: 'axis'
      },
      xAxis: {
        type: 'category',
        boundaryGap: false,
        data: data.category_data
      },
      yAxis: {
        type: 'value',
        min: min,
        max: max,
        splitLine: {
          lineStyle: {
            type: 'dashed'
          }
        }
      },
      series: data.series.map(item => ({
        name: item.name,
        type: 'line',
        smooth: true,
        data: item.data
      }))
    };
  },

  // 事件处理
  bindDeviceChange(e) {
    this.setData({
      device_picker_index: e.detail.value
    });
  },

  bindDateChange(e) {
    this.setData({
      date: e.detail.value
    });
  },

  showChart() {
    const option = this.fetchChartData()
    // console.log(option)
  },

  // 生命周期
  onLoad() {
    this.init_date();
    this.fetchDevices();
  },

});